package timbap.artwork.storage;

import timbap.visualizer.api.model.PlaylistEntry;
import timbap.visualizer.impl.context.textures.AbstractP5TextureCacheManager;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

public class ArtworkFileUpdater implements ActionListener {

    PlaylistEntry playlistEntry;
    JLabel actualImageViewer;
    int resultIndex;

    public ArtworkFileUpdater(final PlaylistEntry pPlaylistEntry, JLabel pActualImageViewer, final int pResultIndex) {
        playlistEntry = pPlaylistEntry;
        actualImageViewer = pActualImageViewer;
        resultIndex = pResultIndex;
    }

    public void actionPerformed(final ActionEvent e) {
        ResultStorageManager tResultStorageManager = ResultStorageManager.getInstance();
        InputStream tImageDataFromTempFile = tResultStorageManager.loadFromTempDir(playlistEntry, resultIndex);
        tResultStorageManager.writeArtworkFile(tImageDataFromTempFile, playlistEntry);
        updateActualImageViewer();
    }

    private void updateActualImageViewer() {
        File tFile = AbstractP5TextureCacheManager.findArtworkFile(playlistEntry);
        try {
            actualImageViewer.setIcon(new ImageIcon(
                    ImageIO.read(tFile).getScaledInstance(100, -1, Image.SCALE_SMOOTH)));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
